package com.yupi.springbootinit.manager;

import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.ThrowUtils;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author vvv
 * @date 2023-12-01 14 03
 * discription
 */
@Service
public class RateLimiterManager {

    @Resource
    private RedissonClient redissonClient;

    public void rateLimiterByKey(String key) {
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        rateLimiter.setRate(RateType.OVERALL, 2, 1, RateIntervalUnit.SECONDS);

        boolean isSuccess = rateLimiter.tryAcquire();
        ThrowUtils.throwIf(!isSuccess, ErrorCode.TOO_MANY_REQUEST);
    }
}
